{{ $paginator := .Paginator }}
{{ $adjacent_links := 2 }}
{{ $max_links := (add (mul $adjacent_links 2) 1) }}
{{ $lower_limit := (add $adjacent_links 1) }}
{{ $upper_limit := (sub $paginator.TotalPages $adjacent_links) }}

{{ if gt $paginator.TotalPages 1 }}

  <ul class="pagination">

    {{ if $paginator.HasPrev }}
      {{ if ne $paginator.PageNumber 1 }}
        <li class="first"><a href="{{ $paginator.First.URL }}">&laquo;</a></li>
      {{ end }}
      <li class="previous"><a href="{{ $paginator.Prev.URL }}">&lsaquo;</a></li>
    {{ end }}

    {{ range $paginator.Pagers }}
      {{ $.Scratch.Set "page_number_flag" false }}
      {{ if gt $paginator.TotalPages $max_links }}
        {{ if le $paginator.PageNumber $lower_limit }}
          {{ if le .PageNumber $max_links }}
            {{ $.Scratch.Set "page_number_flag" true }}
          {{ end }}
        {{ else if ge $paginator.PageNumber $upper_limit }}
          {{ if gt .PageNumber (sub $paginator.TotalPages $max_links) }}
            {{ $.Scratch.Set "page_number_flag" true }}
          {{ end }}
        {{ else }}
          {{ if and (ge .PageNumber (sub $paginator.PageNumber $adjacent_links))
            (le .PageNumber (add $paginator.PageNumber $adjacent_links)) }}
            {{ $.Scratch.Set "page_number_flag" true }}
          {{ end }}
        {{ end }}
      {{ else }}
        {{ $.Scratch.Set "page_number_flag" true }}
      {{ end }}
      {{ if eq ($.Scratch.Get "page_number_flag") true }}
        {{ if eq . $paginator }}
          <li><span>{{ .PageNumber }}</span></li>
        {{ else }}
          <li><a href="{{ .URL }}">{{ .PageNumber }}</a></li>
        {{ end }}
      {{ end }}
    {{ end }}

    {{ if $paginator.HasNext }}
      <li class="next"><a href="{{ $paginator.Next.URL }}">&rsaquo;</a></li>
      {{ if ne $paginator.PageNumber $paginator.TotalPages }}
        <li class="last"><a href="{{ $paginator.Last.URL }}">&raquo;</a></li>
      {{ end }}
    {{ end }}

  </ul>

{{ end }}
